import os
import time
import logging
import configparser
from pathlib import Path
from utils import get_last_commit_hash, create_commit_archive, extract_archive, run_bcompare

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('git_review.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

def load_config():
    """Load and parse the configuration file.
    
    Returns:
        dict: A dictionary containing all settings from the config file.
    Raises:
        configparser.Error: If the config file is missing or invalid.
    """
    config = configparser.ConfigParser()
    config.read('config.ini')
    return config['settings']

def main():
    """Main function to monitor git repository for changes.
    
    Continuously checks the git repository for new commits. When a new commit is detected:
    1. Creates a zip archive of the previous commit
    2. Extracts the archive to the comparison directory
    3. Runs Beyond Compare to show differences
    4. Updates the last known commit hash
    
    The check interval is configurable in config.ini.
    """
    config = load_config()
    
    # Validate paths from config
    git_dir = Path(config['git_work_dir'])
    extract_dir = Path(config['extract_dir'])
    bcompare_path = Path(config['bcompare_path'])
    
    # Create extract directory if it doesn't exist
    extract_dir.mkdir(parents=True, exist_ok=True)
    
    interval = int(config['check_interval'])
    
    logger.info(f"Validating git directory: {git_dir}")

    # Initialize last commit record
    last_commit = get_last_commit_hash(git_dir)
    
    logger.info(f"Starting git commit monitor for {git_dir}")
    logger.info(f"Will compare with {extract_dir} using {bcompare_path}")
    
    while True:
        current_commit = get_last_commit_hash(git_dir)
        
        if current_commit != last_commit:
            logger.info(f"New commit detected: {current_commit}")
            logger.info("Starting comparison process...")
            
            try:
                # 1. Create zip archive
                logger.info("Creating zip archive of previous commit...")
                zip_path = create_commit_archive(git_dir)
                logger.info(f"Archive created at: {zip_path}")
                
                # 2. Extract to target directory
                logger.info(f"Extracting archive to: {extract_dir}")
                extract_archive(zip_path, extract_dir)
                logger.info("Extraction completed successfully")
                
                # 3. Run Beyond Compare
                logger.info("Launching Beyond Compare...")
                run_bcompare(bcompare_path, git_dir, extract_dir)
                logger.info("Comparison completed")
            except Exception as e:
                logger.error(f"Error during comparison process: {str(e)}")
                raise
            
            # Update last commit
            last_commit = current_commit
            
        time.sleep(interval)

if __name__ == "__main__":
    main()